<!--添加修改角色信息-->
<template>
  <a-modal v-model="showAddTable" :mask-closable="false" :closable="false" :width="900"
           :title="title ? '新增订单' : '编辑订单'"
           :maskClosable="false"
           :destroyOnClose="true">
    <a-form :form="form" @keydown.native.enter.prevent="saveApply" class="modelSearch">
      <a-row>
        <a-col span="12">
          <a-form-item label="订单名称：" prop="name" v-bind="formStyle">
            <a-input
                placeholder="请输入物料名称" ref="re"
                v-decorator="[
                        'name',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="订单编号：" prop="orderCode" v-bind="formStyle">
            <a-input
                placeholder="请输入订单编号" ref="re"
                v-decorator="[
                        'orderCode',
                        {
                            rules: [
                                { required: true, message: '请输入英文、数字或下划线字符' },
                                { validator: this.verify.validateID.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="供货商：" prop="supplier" v-bind="formStyle">
            <a-input
                placeholder="请输入供货商" ref="re"
                v-decorator="[
                        'supplier',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="供货商电话：" prop="supplierPhone" v-bind="formStyle">
            <a-input
                placeholder="请输入供货商电话" ref="re"
                v-decorator="[
                        'supplierPhone',
                        {
                            rules: [
                                { required: true, message: '请输入合法联系方式' },
                                { validator: this.verify.validatePhone.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="采购人：" prop="purchaser" v-bind="formStyle">
            <a-input
                placeholder="请输入采购人" ref="re"
                v-decorator="[
                        'purchaser',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="采购人电话：" prop="purchaserPhone" v-bind="formStyle">
            <a-input
                placeholder="请输入采购人电话" ref="re"
                v-decorator="[
                        'purchaserPhone',
                        {
                            rules: [
                                { required: true, message: '请输入合法联系方式' },
                                { validator: this.verify.validatePhone.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="采购时间：" prop="procureTime" v-bind="formStyle" required>
            <a-date-picker
                format="YYYY-MM-DD HH:MM:SS"
                v-model="procureTime"
                showTime
                placeholder="采购时间"
                style="width: 100%"
                v-decorator="['procureTime', { rules: [{ required: true, message: '选择采购时间' }] }]"
            />
          </a-form-item>
        </a-col>
        <a-col span="12">
          <a-form-item label="采购原因：" prop="procureReason" v-bind="formStyle">
            <a-input
                placeholder="请输入采购原因" ref="re"
                v-decorator="[
                        'procureReason',
                        {
                            rules: [
                                { required: true, message: '请输入汉字、字母、数字、_或-字符' },
                                { validator: this.verify.validateName.bind(this) }
                            ],
                            getValueFromEvent: event => {
                                return this.verify.formalSpace(event)
                            }
                        }
                    ]"
            />
          </a-form-item>
        </a-col >
      </a-row>
      <a-row>
        <a-col span="12">
          <a-form-item label="采购物料：" prop="materialList" v-bind="formStyle" required>
            <a-button type="primary" size="default" @click="addMaterial()">新增物料</a-button>
          </a-form-item>
        </a-col>
      </a-row>

      <a-table :columns="columns" :dataSource="detail" :rowKey="record => record.index" style="height: 300px;overflow-y: auto"
               :pagination="false">
        <span slot="goodName" slot-scope="text, record, index">
          <a-select
              :key="'goodName'+index+record.rowIndex"
              placeholder="请选物料"
              v-model="record.goodId"
              @select="changeMaterialList($event,index)"
          >
              <a-select-option v-for="item in materialSelectList" :value="item.value"
                               :key="item.value">{{item.label }}
              </a-select-option>
            </a-select>
        </span>
        <span slot="goodNum" slot-scope="text, record, index">
          <a-input-number v-model="record.goodNum" :key="'goodNum'+index+record.rowIndex"
              placeholder="数量" @change="changeInput($event,'goodNum',index)"  :min="0" :max="100000" :precision="0" />
        </span>
        <span slot="unitPrice" slot-scope="text, record, index">
          <a-input-number v-model="record.unitPrice" :key="'unitPrice'+index+record.rowIndex"
              placeholder="单价" @change="changeInput($event,'unitPrice',index)"  :min="0" :max="100000000" :step="0.01" />
        </span>
        <span slot="operation" slot-scope="text, record, index" class="table-operation">
                        <a @click="removeMaterial(index)">
                                          删除</a>
                </span>
      </a-table>
    </a-form>
    <div slot="footer">
      <a-button type="default" size="default" @click="cancelApply()">取消</a-button>
      <a-button type="primary" size="default" @click="saveApply()">确定</a-button>
    </div>
  </a-modal>
</template>

<script>
import verify from 'libs/verify'
import AFormItem from 'ant-design-vue/es/form/FormItem'
import moment from "moment";
import Decimal from 'decimal.js';

export default {
  name: 'addEdit',
  components: {
    AFormItem,
    verify
  },
  data() {
    return {
      verify,
      form: this.$form.createForm(this),
      showAddTable: false,
      input: false,
      procureTime: '',
      materialList: '',
      rowIndex: 10,
      detail:[],
      detailObj:{
        rowIndex:0,
        orderCode:'',
        goodCode:'',
        goodName:'',
        goodNum:'',
        unitPrice:'',
        allPrice:'',
      },
      columns: [
        {title: '选择物料', dataIndex: 'goodName', key: 'goodName',  scopedSlots: {customRender: 'goodName'}},
        {title: '采购数量', dataIndex: 'goodNum', key: 'goodNum', width: '15%', scopedSlots: {customRender: 'goodNum'}},
        {title: '单价（元）', dataIndex: 'unitPrice', key: 'unitPrice', width: '15%', scopedSlots: {customRender: 'unitPrice'}},
        {title: '总价（元）', dataIndex: 'allPrice', key: 'allPrice', width: '20%'},
        {title: '操作', key: 'operation', width: '10%', scopedSlots: {customRender: 'operation'}}
      ],
    }
  },
  computed: {
    materialSelectList() {
      return this.$store.state.materialManage.materialSelectList
    },
    formStyle() {
      return this.$store.state.common.formStyle
    }
  },
  props: {

    title: {
      type: Boolean,
      required: true
    },
    objDTO: {
      type: Object,
      required: true
    }
  },
  watch: {},
  methods: {

    changeMaterialList(value,index){
      let materialSelectList = this.materialSelectList;
      let materialObj = {};
      for (let i in materialSelectList){
        if (value === materialSelectList[i].record.recordId){
          materialObj = materialSelectList[i].record
        }
      }
      this.detail[index].goodCode =materialObj.goodsCode
      this.detail[index].goodName =materialObj.name
    },
    addMaterial(){
      this.detailObj = {
        rowIndex:this.rowIndex,
        orderCode:'',
        goodCode:'',
        goodName:'',
        goodNum:'',
        unitPrice:'',
        allPrice:'',
      }
      this.rowIndex = this.rowIndex+1
      this.detail.push(this.detailObj)
    },
    removeMaterial(index){
      this.detail.splice(index,1)
    },
    changeInput(value,prop,index){
      this.detail[index][prop] = value
      if (prop === 'goodNum' || prop === 'unitPrice'){
        let goodNum = new Decimal(this.detail[index].goodNum)
        let unitPrice = new Decimal(this.detail[index].unitPrice)
        this.detail[index]['allPrice'] = goodNum.times(unitPrice).toFixed(2)
      }
      },
    /**
     * Function    : saveApply
     * Description : 打开弹框
     * Input       : none
     * Return      : none
     */
    showModal() {
      this.showAddTable = true
      this.rowIndex = 0
      this.detail=[]
      this.detailObj={
        rowIndex:0,
            orderCode:'',
            goodCode:'',
            goodName:'',
            goodNum:'',
            unitPrice:'',
            allPrice:''
      }
    },
    /**
     * Function    : showEdit
     * Description : 编辑时显示
     * Input       : opt单个所有数据
     * Return      : none
     */
    showEdit(opt) {
      this.showAddTable = true
      this.id = opt.recordId
      this.rowIndex = 10
      this.detail=[]
      this.detailObj={
        rowIndex:0,
        orderCode:'',
        goodCode:'',
        goodName:'',
        goodNum:'',
        unitPrice:'',
        allPrice:''
      }
      let _this = this;
      _this.$store.dispatch('getOrderInfo', {recordId: opt.recordId}).then(response => {
        let orderInfo = {}
        if (response.code === 0) {
          orderInfo = response.data
          _this.procureTime = moment(orderInfo.procureTime).format('YYYY-MM-DD HH:MM:SS')
          console.log(this.procureTime)
          orderInfo.procureTime = _this.procureTime
          _this.pickMaterialSelect(orderInfo.detail)
          _this.$nextTick(() => {
            _this.form.setFieldsValue(_this.$pick(orderInfo, [
              'name', 'orderCode', 'procureReason', 'purchaser','procureTime',
              'purchaserPhone', 'supplier', 'supplierPhone'
            ]))
            _this.form.setFieldsValue(_this.$pick({procureTime:_this.procureTime}, ['procureTime'
            ]))
          })
        } else {
          _this.$message.error(response.message)
        }
      })

    },

    pickMaterialSelect(materialDetailList) {
      let materialSelectList = this.materialSelectList;
      let detailList = []
      for (let i in materialDetailList) {
        let materialDetail = materialDetailList[i]
        for (let index in materialSelectList) {
          let materialObj = materialSelectList[index].record;
          if (materialObj.goodsCode === materialDetail.goodCode) {
            materialDetail['goodId'] = materialObj.recordId
          }
        }
        detailList.push(materialDetail)
      }
      this.detail = detailList;
    },

    /**
     * Function    : saveApply
     * Description : 角色信息新增、编辑保存
     * Input       : name
     * Return      : none
     */
    saveApply() {
      let _this = this
      if (_this.detail.length === 0){
        this.$message.error('物料不可为空')
        return
      }
      this.form.validateFields((err, value) => {
        if (!err) {
          let para = {}
          for (let index in _this.detail){
            _this.detail[index]['orderCode'] =value.orderCode
          }
          para.name = value.name
          para.orderCode = value.orderCode
          para.supplier = value.supplier
          para.supplierPhone = value.supplierPhone
          para.purchaser = value.purchaser
          para.procureTime = moment(value.procureTime).format('YYYY-MM-DD HH:MM:SS')
          para.purchaserPhone = value.purchaserPhone
          para.procureReason = value.procureReason
          para.detail = this.detail
          if (!this.title) {
            para.recordId = this.id
          }
          this.$store.dispatch('saveOrderAct', para).then(response => {
            this.showAddTable = false
            if (response.code === 0) {
              this.$emit('init')
              this.$message.success(response.message)
            } else {
              this.$message.error(response.message)
            }
          })
        }
      })
    },

    /**
     * Function    : cancelApply
     * Description : 取消弹出框
     * Input       : val
     * Return      : none
     */
    cancelApply() {
      this.showAddTable = false
      let _this = this
      setTimeout(function () {
        _this.form.resetFields()
      }, 100)
    },
    initData() {
      this.$store.dispatch('getMaterialSelectListAct', {})
    }

  },

  created() {
    this.initData()
  }
}
</script>

<style>
.ant-table-thead {
  position: sticky;
  top: 0px;
  z-index: 1;
}
</style>
